package com.cloud.rou.im.router.handler;

import com.cloud.rou.im.msg.Msg;
import com.cloud.rou.im.protocol.transfer.DataPacketFactory;
import com.cloud.rou.im.router.context.ChannelAndInstance;
import com.cloud.rou.im.router.context.ImServerInstanceContext;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-11-09 20:41
 */
@Slf4j
public class ConnectorService {

    private ImServerInstanceContext context  ;

    public ConnectorService() {
       this.context =ImServerInstanceContext.getInstance();
    }

    /**
     * Process the chat message and forward it to the next client
     *
     * @param msg
     */
    public void doChatForward(ChannelHandlerContext ctx,Msg msg) {
        Map<Long, ChannelAndInstance> instanceMap = context.getInstanceMap();
        instanceMap.forEach((aLong, channelAndInstance) -> {
            Channel channel = channelAndInstance.getChannel();
            if(ctx.channel()!=channel){
                doWriteAndFlush(channel,msg);
            }
        });

    }

    private ChannelFuture doWriteAndFlush(Channel channel ,Msg msg) {
        return channel.writeAndFlush(DataPacketFactory.getPacket(msg));
    }



}
